<!--suppress ALL, JSUnusedAssignment -->
<script setup lang="ts" xmlns="http://www.w3.org/1999/html">

import UpdateFile from "@/components/upload/File.vue";
import {ref, toRaw, watch, reactive} from "vue";
import ShareContainer from "@/components/common/ShareContainer.vue";
import {assetDelete, assetSearch} from "@/api/home";
import {downloadFile} from "@/api/downloader";
import type {AssetMetadata} from "@/types/AssetMetadata";

import {iconClass} from "@/types/DigitalFormatEnum";
import {t as $t} from "@/plugins/i18nPlugin";
import {confirms, messages} from "@/utils/currency";
import {useStore} from "@/stores";
import ListVsiews from "@/components/common/ListView.vue";
import util from "@/utils/util";
import {convertDateTimeToLocal, formatDateTime, fromISO} from '@yeying-community/yeying-web3'

// 操作
const generateActions = (row: AssetMetadata) => [
    {
        label: "下载",
        icon: "icon-arrow-down-rectangle",
        callback: () => handleDownload(row)
    },
    {
        label: "删除",
        icon: "icon-shanchu",
        callback: () => handleDelete(row)
    },
    {
        label: "重命名",
        icon: "icon-zhongmingming",
        callback: () => addFileVisible(row)
    },
    {
        label: "分享",
        icon: "icon-fangyuanyun_benrengongxiangguanli",
        callback: () => openShareDialog(row)
    },
    {
        label: "详情",
        icon: "icon-xiangqing",
        callback: () => setDetail(row)
    }
];
const store = useStore();
const isMobile = ref(store.isMobile);
const dialogWidth = isMobile.value ? "90%" : "";
// 状态管理方法
const setDetail = (value: AssetMetadata) => store.setDetail(value);

const nameSpaceValue = ref("");

// 表格数据
const tableData = ref<AssetMetadata[]>([]);
const searchAssetCondition = reactive({
    hash: "",
    name: "",
    namespaceId: store.namespaceId,
});

// 搜索资产，根据条件和分页参数查询资产列表
const getList = async () => {
  const assetSearchData = await assetSearch(searchAssetCondition);
  store.setTableData(assetSearchData)
  tableData.value = store.tableData.filter(item => item.namespaceId === nameSpaceValue.value);
};

getList();


// 新建文件夹浮层显示状态
const dialogAddFileVisible = ref(false);

// 表单数据
const ruleForm = ref<AssetMetadata>();

// 打开新建/编辑对话框
const addFileVisible = (item: AssetMetadata) => {
    ruleForm.value = JSON.parse(JSON.stringify(item, (_key, value) => {
        if (typeof value === "bigint") {
            return value.toString();
        }
        return value;
    }));
    dialogAddFileVisible.value = true;
};


// 资产信息 新增和编辑成功
const handleSuccess = (data: string, msg = "新增") => {
    getList();
    if (data) {
        messages(msg + "成功", "success");
    }
};

// 删除逻辑
const handleDelete = async ({ namespaceId, hash }: AssetMetadata) => {
    confirms().then(async () => {
        // 确认发出删除请求
        await assetDelete(namespaceId, hash);
        handleSuccess("del", "删除");
    });
};

// 文件下载 downloads
const handleDownload = async ({ namespaceId, hash, name }: AssetMetadata) => {
    await downloadFile(namespaceId, hash, name);
    // messages('下载成功', 'success');
};


const multipleDownload =() => {
  if(multipleSelection.value){
    multipleSelection.value.forEach(async (item) => {
      const { namespaceId, hash, name } = toRaw(item);
      await downloadFile(namespaceId, hash, name);
    });
  }
}

const multipleDelete = () => {
  if(multipleSelection.value){
    multipleSelection.value.forEach(async (item) => {
      const { namespaceId, hash } = toRaw(item);
      await assetDelete(namespaceId, hash);
      handleSuccess("del", "删除");
    });
  }
}

// 多选状态管理
const multipleSelection = ref<AssetMetadata[]>([]);

// 更新选中项
const updateSelection = (val: AssetMetadata[]) => {
    // 触发父组件的事件，更新选中项
    multipleSelection.value = val;

};

const dialogShareVisible = ref(false); // 分享对话框显示状态
// 分享链接
const shareLink = ref("");

// 打开分享对话框
const openShareDialog = (item: AssetMetadata) => {
    ruleForm.value = { ...item };
    dialogShareVisible.value = true;
};


const dealUpdatedAt = (updatedAt:string) =>{
  return formatDateTime(convertDateTimeToLocal(fromISO(updatedAt)),"yyyy-MM-dd HH:mm:ss");
};


watch(
  () => store.namespaceId,
  (newVal, _) => {
    nameSpaceValue.value = newVal;
    getList();
  },
  { immediate: true }
)


const canEdit = ref<boolean>(true);

</script>

<template>
  <span class="upload_file_tips">上传进度，请到传输记录中查看</span>
    <div class="flexCenter mb10" style="margin-top: 10px;">
        <UpdateFile class="mr10" :namespaceId="nameSpaceValue"  :isItEncrypted="false" uploadButtonText="明文上传" @uploadSuccess="getList" ></UpdateFile>
        <UpdateFile class="mr10" :namespaceId="nameSpaceValue"  :isItEncrypted="true" uploadButtonText="密文上传" @uploadSuccess="getList" ></UpdateFile>

        <div class="flexCenter" v-if="multipleSelection.length">
            <el-button type="primary">
                <span class="iconfont icon-arrow-down-rectangle"></span>
                <span class="pljh" v-if="!isMobile" @click="multipleDownload">{{$t('assets.download')}}</span>
            </el-button>

            <el-button type="primary">
                <span class="iconfont icon-shanchu"></span>
                <span class="pljh" v-if="!isMobile" @click="multipleDelete">{{$t('assets.delete')}}</span>
            </el-button>
        </div>
    </div>
    <ListVsiews :data="tableData" :generateActions="generateActions" @update:selection="updateSelection">
        <template #dynamic-columns>
            <el-table-column :label="$t('assets.tabel.name')" width="auto">
                <template #default="scope">
                    <div class="flexCenter">
                        <span class="iconfont" :class="iconClass[scope.row.format]"></span>
                      <div  v-html="scope.row.name" ref="divInput"   :contenteditable="canEdit"></div>
<!--                        <span class="iconfont icon-km-edit pointer" @click.stop="addFileVisible(scope.row)"></span>-->
                    </div>
                </template>
            </el-table-column>
            <template v-if="!isMobile">
                <el-table-column :label="$t('assets.tabel.time')" width="200">
                    <template #default="scope">
                        <span>{{ dealUpdatedAt(scope.row.updatedAt) || '-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('assets.tabel.size')" width="80">
                    <template #default="scope">
                        <span>{{ util.formatFileSize(Number(scope.row.size)) || '-' }}</span>
                    </template>
                </el-table-column>
            </template>
        </template>
        <template #operate="{ scope }">
            <span v-if="!isMobile" class="iconfont icon-fangyuanyun_benrengongxiangguanli pointer"
                @click="openShareDialog(scope.row)"></span>
        </template>
    </ListVsiews>

    <el-dialog v-model="dialogShareVisible" title="分享" @close="dialogShareVisible = false" :width="dialogWidth" style="border:1px solid red;">
        <ShareContainer v-if="dialogShareVisible && ruleForm" :assetMetadata="ruleForm" :shareLink="shareLink"
            @close="dialogShareVisible = false" />
    </el-dialog>
</template>

<style lang="scss" scoped>
.upload_file_tips{
  font-size: 12px;
  color: #606266;
}
.select_Namespace_box {
    position: absolute;
    top: 0;
    left: 30px;


    .iconfont {
        padding-right: 10px;
    }

    .select_Namespace {
        max-width: 240px;

        :deep(.el-select__wrapper) {
            border: none;
            /* 移除边框 */
            background-color: transparent;
            /* 移除背景色 */
        }
    }


}

.select_Namespace_mobile {
    justify-content: flex-end;
    right: 0;
    top: -6px;
    left: 0;

    .select_Namespace {
        width: 50%;
    }
}
</style>